package xx.pro.shiro.config;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.StringUtils;
import xx.pro.shiro.entity.SysPermissions;
import xx.pro.shiro.entity.SysRole;
import xx.pro.shiro.entity.SysUser;
import xx.pro.shiro.service.SysUserService;

import javax.annotation.Resource;

public class CustomerRealm extends AuthorizingRealm {

    @Resource
    SysUserService sysUserService;

    /**
     * 授权逻辑
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权逻辑PrincipalCollection");
        //获取登录用户名
        String userName = (String) principalCollection.getPrimaryPrincipal();
        SysUser sysUser = this.sysUserService.queryUserInfoByUserInfo(userName);

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        for (SysRole role : sysUser.getSysRoleList()) {
            //添加角色
            authorizationInfo.addRole(role.getCode());
            //添加权限
            for (SysPermissions permissions : sysUser.getPermissionsSet()) {
                authorizationInfo.addStringPermission(permissions.getCode());
            }
        }
        return authorizationInfo;
    }

    /**
     * 认证逻辑
     * @param authenticationToken
     * @return
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        System.out.println("执行了=>认证逻辑AuthenticationToken");
        if(authenticationToken.getPrincipal()==null){
            return null;
        }
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        SysUser sysUser = this.sysUserService.queryUserInfoByUserName(token.getUsername());

        if(sysUser == null){
            return null;
        }
        return  new SimpleAuthenticationInfo(sysUser.getUsername(), sysUser.getPassword(), getName());
    }
}
